import datetime
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from mgmt import pagination
from sms import views as sms_api
from ymiot import views as ymiot_api
from teacher.auth import TeacherJWT
from mgmt.models import Batch
from mgmt.models import Security
from mgmt.models import BatchCar
from mgmt.serializers import BatchCarSerl
from mgmt.serializers import BatchSerl
from mgmt.serializers import SecuritySerl
from persons.serializers import PersonBriefSerl
from cars.models import Car
from student.models import StudentInvite
from student.models import StudentInvitePerson
from student.models import StudentInviteVerify
from student.models import StudentModel
from student.serializers import StudentInviteDetSerl
from student.serializers import StudentInvitePersonSerl
from student.serializers import StudentInviteVerifySerl
from student.serializers import StudentSerl
from visitor.models import VisitorModel
from visitor.models import VisitorApplyVerify
from visitor.models import VisitorApplyPerson
from visitor.models import VisitorApplyCar
from visitor.models import VisitorApply
from visitor.serializers import VisitorSerl
from visitor.serializers import VisitorApplyVerifySerl
from visitor.serializers import VisitorApplyPersonSerl
from visitor.serializers import VisitorApplyDetSerl
from visitor.serializers import VisitorApplyCarSerl
from teacher.models import TeacherInvite
from teacher.models import TeacherInviteCar
from teacher.models import TeacherInvitePerson
from teacher.models import TeacherInviteVerify
from teacher.models import TeacherModel
from teacher.serializers import TeacherInviteCarSerl
from teacher.serializers import TeacherInviteDetSerl
from teacher.serializers import TeacherInvitePersonSerl
from teacher.serializers import TeacherInviteVerifySerl
from teacher.serializers import TeacherSerl


class BatchIndexApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def get(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        # 教职工
        request_teacher = request.user
        result["data"]["teacher"] = TeacherSerl(request_teacher).data
        batchLst = []
        now = datetime.datetime.now()
        for batch in Batch.objects.filter(enddate__gte=now):
            batchItm = {}
            batchItm["id"] = batch.id
            batchItm["title"] = batch.title
            batchItm["isfree"] = batch.isfree
            batchItm["startdate"] = batch.startdate
            batchItm["enddate"] = batch.enddate
            batchItm["carCount"] = BatchCar.objects.filter(batch=batch).count()
            batchLst.append(batchItm)
        result["data"]["batchLst"] = batchLst
        return Response(result)


class BatchAddApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def post(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        request_teacher = request.user
        title = request.data["title"]
        freeFlag = request.data["isfree"]
        if freeFlag:
            isfree = 1
        else:
            isfree = 0
        startdate = request.data["startdate"]
        enddate = request.data["enddate"]
        batch = Batch()
        batch.creater = request_teacher
        batch.title = title
        batch.isfree = isfree
        batch.startdate = startdate
        batch.enddate = enddate
        batch.save()
        carLst = request.data["carLst"]
        print("carLst")
        print(carLst)
        for carItm in carLst:
            print("carItm")
            print(carItm)
            # car
            try:
                car = Car.objects.get(plate=carItm)
            except Car.DoesNotExist:
                car = Car()
                car.plate = carItm
                car.save()
            # batchCar
            batchCar = BatchCar()
            batchCar.batch = batch
            batchCar.car = car
            batchCar.creater = request_teacher
            batchCar.save()
            # 增加当日访客车辆
            today = datetime.datetime.now().date()
            startDate = datetime.datetime.strptime(batch.startdate, "%Y-%m-%d").date()
            if startDate == today:
                print("增加当日访客车辆")
                now = datetime.datetime.now()
                beginTimeTxt = (now + datetime.timedelta(minutes=5)).strftime(
                    "%Y-%m-%d %H:%M:%S"
                )
                endTimeTxt = now.replace(hour=23, minute=59, second=59).strftime(
                    "%Y-%m-%d %H:%M:%S"
                )
                response_add = ymiot_api.add_visitor_car(
                    car.plate, beginTimeTxt, endTimeTxt
                )
                if response_add["code"] == 0:
                    response_data = response_add["data"]
                    response_visitorNo = response_data["visitorNo"]
                    response_beginTime = response_data["beginTime"]
                    response_endTime = response_data["endTime"]
                    car.status = 2
                    car.visitorNo = response_visitorNo
                    car.beginTime = response_beginTime
                    car.endTime = response_endTime
                    car.save()
                    # 处理车辆日志
                    # logName = f"<教师>{requestTeacher.name}"
                    # makeCarLog(car.id, logName, "访客车辆状态添加成功")
                    # smsvars = {
                    #     "role": requestTeacher.name + "老师",
                    #     "plate": car.plate,
                    #     "time1": car.beginTime,
                    # }
                    # sendSms(2, requestTeacher.phone, smsvars)
        return Response(result)


class BatchDetApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def get(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        batchId = request.GET.get("batchId")
        batch = Batch.objects.get(id=batchId)
        result["data"]["batch"] = BatchSerl(batch).data
        carLst = BatchCar.objects.filter(batch=batch)
        result["data"]["carLst"] = BatchCarSerl(carLst, many=True).data
        return Response(result)


class BatchDelApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def post(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        batchId = request.data["batchId"]
        try:
            batch = Batch.objects.get(id=batchId)
            batch.delete()
            result["msg"] = "删除成功"
        except Exception as e:
            result["code"] = 500
            result["msg"] = "删除失败"
        return Response(result)


class SecurityDetApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def get(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        # 安全等级
        security = Security.objects.get(pk=1)
        result["data"]["security"] = SecuritySerl(security).data
        return Response(result)


class SecurityLevelApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def post(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        newlevel = request.data["newlevel"]
        security = Security.objects.get(pk=1)
        security.level = newlevel
        try:
            security.save()
        except Exception as e:
            result["code"] = 500
            result["msg"] = "保存失败"
        return Response(result)


class MemberCountApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def get(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        count = {}
        count["teacher"] = TeacherModel.objects.count()
        count["visitor"] = VisitorModel.objects.count()
        count["student"] = StudentModel.objects.count()
        result["data"]["count"] = count
        return Response(result)


class MemberCheckPhoneApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def post(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        role = request.data["role"]
        phone = request.data["phone"]
        memberFlag = 0
        if role == "student":
            try:
                student = StudentModel.objects.get(phone=phone)
                memberFlag = 1
                result["data"]["member"] = StudentSerl(student).data
            except StudentModel.DoesNotExist:
                memberFlag = 0
        elif role == "visitor":
            try:
                visitor = VisitorModel.objects.get(phone=phone)
                memberFlag = 1
                result["data"]["member"] = VisitorSerl(visitor).data
            except VisitorModel.DoesNotExist:
                memberFlag = 0
        elif role == "teacher":
            try:
                teacher = TeacherModel.objects.get(phone=phone)
                memberFlag = 1
                result["data"]["member"] = TeacherSerl(teacher).data
            except TeacherModel.DoesNotExist:
                memberFlag = 0
        result["data"]["memberFlag"] = memberFlag
        return Response(result)


class MemberDelApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def post(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        # 教职工
        request_teacher = request.user
        result["data"]["teacher"] = TeacherSerl(request_teacher).data
        role = request.data["role"]
        if role == "student":
            memberid = request.data["memberid"]
            student = StudentModel.objects.get(id=memberid)
            try:
                student.delete()
            except Exception:
                result["code"] = 500
                result["msg"] = "删除失败"
        elif role == "visitor":
            memberid = request.data["memberid"]
            visitor = VisitorModel.objects.get(id=memberid)
            try:
                visitor.delete()
            except Exception:
                result["code"] = 500
                result["msg"] = "删除失败"
        elif role == "teacher":
            memberid = request.data["memberid"]
            teacher = TeacherModel.objects.get(id=memberid)
            try:
                teacher.delete()
            except Exception:
                result["code"] = 500
                result["msg"] = "删除失败"
        return Response(result)


class MemberUpdateApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def post(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        # 教职工
        request_teacher = request.user
        result["data"]["teacher"] = TeacherSerl(request_teacher).data
        role = request.data["role"]
        if role == "student":
            memberid = request.data["memberid"]
            name = request.data["name"]
            dept = request.data["dept"]
            student = StudentModel.objects.get(id=memberid)
            student.name = name
            student.dept = dept
            try:
                student.save()
            except Exception:
                result["code"] = 500
                result["msg"] = "更新失败"
        elif role == "visitor":
            memberid = request.data["memberid"]
            name = request.data["name"]
            dept = request.data["dept"]
            visitor = VisitorModel.objects.get(id=memberid)
            visitor.name = name
            visitor.dept = dept
            try:
                visitor.save()
            except Exception:
                result["code"] = 500
                result["msg"] = "更新失败"
        elif role == "teacher":
            memberid = request.data["memberid"]
            name = request.data["name"]
            dept = request.data["dept"]
            issecurity = request.data["issecurity"]
            isleader = request.data["isleader"]
            teacher = TeacherModel.objects.get(id=memberid)
            teacher.name = name
            teacher.dept = dept
            teacher.is_security = issecurity
            teacher.is_leader = isleader
            try:
                teacher.save()
            except Exception:
                result["code"] = 500
                result["msg"] = "更新失败"
        return Response(result)


class MemberAddApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def post(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        role = request.data["role"]
        phone = request.data["phone"]
        if role == "student":
            name = request.data["name"]
            dept = request.data["dept"]
            student = StudentModel()
            student.phone = phone
            student.name = name
            student.dept = dept
            try:
                student.save()
            except Exception:
                result["code"] = 500
                result["msg"] = "新增失败"
        elif role == "visitor":
            name = request.data["name"]
            dept = request.data["dept"]
            visitor = VisitorModel()
            visitor.phone = phone
            visitor.name = name
            visitor.dept = dept
            try:
                visitor.save()
            except Exception:
                result["code"] = 500
                result["msg"] = "新增失败"
        elif role == "teacher":
            name = request.data["name"]
            dept = request.data["dept"]
            issecurity = request.data["issecurity"]
            isleader = request.data["isleader"]
            teacher = TeacherModel()
            teacher.phone = phone
            teacher.name = name
            teacher.dept = dept
            teacher.is_security = issecurity
            teacher.is_leader = isleader
            try:
                teacher.save()
            except Exception:
                result["code"] = 500
                result["msg"] = "新增失败"
        return Response(result)


class SheetLstApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def get(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        role = request.GET.get("role")
        if role == "student":
            sheetList = StudentInvite.objects.all().order_by("-updated")[:100]
            sheetLst = []
            for sheetItem in sheetList:
                sheetItm = {}
                sheetItm["id"] = sheetItem.id
                sheetItm["teacherName"] = sheetItem.student.name
                sheetItm["guestName"] = sheetItem.person.name
                sheetItm["status"] = sheetItem.status
                sheetItm["statusText"] = sheetItem.get_status_display()
                sheetItm["when"] = sheetItem.when.strftime("%m-%d %H:%M")
                sheetLst.append(sheetItm)
        elif role == "teacher":
            sheetList = TeacherInvite.objects.all().order_by("-updated")[:100]
            sheetLst = []
            for sheetItem in sheetList:
                sheetItm = {}
                sheetItm["id"] = sheetItem.id
                sheetItm["teacherName"] = sheetItem.teacher.name
                sheetItm["guestName"] = sheetItem.person.name
                sheetItm["status"] = sheetItem.status
                sheetItm["statusText"] = sheetItem.get_status_display()
                sheetItm["when"] = sheetItem.when.strftime("%m-%d %H:%M")
                sheetLst.append(sheetItm)
        elif role == "visitor":
            sheetList = VisitorApply.objects.all().order_by("-updated")[:100]
            sheetLst = []
            for sheetItem in sheetList:
                sheetItm = {}
                sheetItm["id"] = sheetItem.id
                sheetItm["teacherName"] = sheetItem.teacher.name
                sheetItm["guestName"] = sheetItem.visitor.name
                sheetItm["status"] = sheetItem.status
                sheetItm["statusText"] = sheetItem.get_status_display()
                sheetItm["when"] = sheetItem.when.strftime("%m-%d %H:%M")
                sheetLst.append(sheetItm)
        # 1. 实例化分页器对象
        page_obj = pagination.PageNumberPagination()
        # 2. 使用自己配置的分页器调用分页方法进行分页
        page_data = page_obj.paginate_queryset(sheetLst, request)
        # 4. 返回带上一页/下一页连接的页面
        return page_obj.get_paginated_response(page_data)


class SheetDetApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def get(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        # 教职工
        request_teacher = request.user
        result["data"]["teacher"] = TeacherSerl(request_teacher).data
        role = request.GET.get("role")
        sheetId = request.GET.get("sheetId")
        if role == "student":
            sheetItm = StudentInvite.objects.get(id=sheetId)
            result["data"]["sheetData"] = StudentInviteDetSerl(sheetItm).data
            mainPerson = sheetItm.person
            result["data"]["mainPerson"] = PersonBriefSerl(mainPerson).data
            student = sheetItm.student
            result["data"]["teacher"] = StudentSerl(student).data
            #  处理随行人员
            sheetVisitorLst = StudentInvitePerson.objects.filter(invite=sheetItm)
            if sheetVisitorLst.count() == 0:
                result["data"]["sheetPersonFlag"] = 0
            else:
                result["data"]["sheetPersonFlag"] = 1
                result["data"]["sheetPersonList"] = StudentInvitePersonSerl(
                    sheetVisitorLst, many=True
                ).data
            # 审核列表
            verifyList = StudentInviteVerify.objects.filter(invite=sheetItm).order_by(
                "-updated"
            )
            result["data"]["verifyList"] = StudentInviteVerifySerl(
                verifyList, many=True
            ).data
        elif role == "teacher":
            sheetItm = TeacherInvite.objects.get(id=sheetId)
            result["data"]["sheetData"] = TeacherInviteDetSerl(sheetItm).data
            mainPerson = sheetItm.person
            result["data"]["mainPerson"] = PersonBriefSerl(mainPerson).data
            teacher = sheetItm.teacher
            result["data"]["teacher"] = TeacherSerl(teacher).data
            # 处理车辆
            sheetCarLst = TeacherInviteCar.objects.filter(invite=sheetItm)
            if sheetCarLst.count() == 0:
                result["data"]["sheetCarFlag"] = 0
            else:
                sheetCarFlag = 1
                result["data"]["sheetCarFlag"] = sheetCarFlag
                result["data"]["sheetCarList"] = TeacherInviteCarSerl(
                    sheetCarLst, many=True
                ).data
            #  处理随行人员
            sheetVisitorLst = TeacherInvitePerson.objects.filter(invite=sheetItm)
            if sheetVisitorLst.count() == 0:
                result["data"]["sheetPersonFlag"] = 0
            else:
                result["data"]["sheetPersonFlag"] = 1
                result["data"]["sheetPersonList"] = TeacherInvitePersonSerl(
                    sheetVisitorLst, many=True
                ).data
            # 审核列表
            verifyList = TeacherInviteVerify.objects.filter(invite=sheetItm).order_by(
                "-updated"
            )
            result["data"]["verifyList"] = TeacherInviteVerifySerl(
                verifyList, many=True
            ).data
        elif role == "visitor":
            sheetItm = VisitorApply.objects.get(id=sheetId)
            result["data"]["sheetData"] = VisitorApplyDetSerl(sheetItm).data
            mainPerson = sheetItm.visitor
            result["data"]["mainPerson"] = VisitorSerl(mainPerson).data
            teacher = sheetItm.teacher
            result["data"]["teacher"] = TeacherSerl(teacher).data
            # 处理车辆
            sheetCarLst = VisitorApplyCar.objects.filter(apply=sheetItm)
            if sheetCarLst.count() == 0:
                result["data"]["sheetCarFlag"] = 0
            else:
                sheetCarFlag = 1
                result["data"]["sheetCarFlag"] = sheetCarFlag
                result["data"]["sheetCarList"] = VisitorApplyCarSerl(
                    sheetCarLst, many=True
                ).data
            #  处理随行人员
            sheetVisitorLst = VisitorApplyPerson.objects.filter(apply=sheetItm)
            if sheetVisitorLst.count() == 0:
                result["data"]["sheetPersonFlag"] = 0
            else:
                result["data"]["sheetPersonFlag"] = 1
                result["data"]["sheetPersonList"] = VisitorApplyPersonSerl(
                    sheetVisitorLst, many=True
                ).data
            # 审核列表
            verifyList = VisitorApplyVerify.objects.filter(apply=sheetItm).order_by(
                "-updated"
            )
            result["data"]["verifyList"] = VisitorApplyVerifySerl(
                verifyList, many=True
            ).data
        return Response(result)


class SheetUpdApi(APIView):
    permission_classes = (IsAuthenticated,)
    authentication_classes = [TeacherJWT]

    def post(self, request, format=None):
        result = {"code": 0, "msg": "ok", "data": {}}
        # 教职工
        request_teacher = request.user
        result["data"]["teacher"] = TeacherSerl(request_teacher).data
        role = request.data["role"]
        sheetId = request.data["sheetId"]
        newStatus = request.data["newStatus"]
        if role == "student":
            sheetItm = StudentInvite.objects.get(id=sheetId)
            sheetItm.status = newStatus
            sheetItm.save()
        elif role == "teacher":
            sheetItm = TeacherInvite.objects.get(id=sheetId)
            sheetItm.status = newStatus
            sheetItm.save()
        elif role == "visitor":
            sheetItm = VisitorApply.objects.get(id=sheetId)
            sheetItm.status = newStatus
            sheetItm.save()
        # TODO 5 和 7 的车辆处理
        return Response(result)
